<template>
  <el-dialog
    :before-close="cancel"
    :close-on-click-modal="false"
    :visible.sync="editUserGroupDialogVisible"
    class="vc-dialog-form"
    title="修改用户组"
    width="480px"
  >
    <el-form :model="editForm" :rules="rules" label-width="100px" ref="editForm" size="small">
      <el-form-item label="上级用户组" prop="pid">
        <el-tree-select
          :data="ugTreeData"
          :default-expanded-keys="ugTreeData.length ? [ugTreeData[0].id] : []"
          :props="defaultProps"
          clearable
          v-model="editForm.pid"
        ></el-tree-select>
      </el-form-item>
      <el-form-item label="用户组名称" prop="name">
        <el-input clearable maxlength="20" v-model="editForm.name"></el-input>
      </el-form-item>
    </el-form>

    <span class="dialog-footer" slot="footer">
      <el-button @click="cancel" size="small">取消</el-button>
      <el-button :disabled="disabled" @click="save" size="small" type="primary">保存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { validateInput } from '@/utils/validator'
export default {
  name: 'editUserGroup',

  props: ['editUserGroupDialogVisible'],
  data () {
    return {
      defaultProps: {
        id: 'id',
        label: 'name',
        children: 'children',
        isLeaf: 'isLeaf'
      },
      editForm: {
        id: '',

        name: '',
        pid: ''
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入用户组名称',
            trigger: 'blur'
          },
          { validator: validateInput, trigger: 'blur' }
        ]
      },
      disabled: false,
      readonly: true
    }
  },
  computed: {
    editMenuData () {
      return this.$parent.editMenuData
    },
    ugTreeData () {
      var temp = this.$parent.ugTreeDataHasTop

      return temp
    }
  },
  watch: {
    editUserGroupDialogVisible (val) {
      if (!val) return

      this.$refs.editForm && this.$refs.editForm.resetFields()

      this.editForm.id = this.editMenuData.id
      this.editForm.name = this.editMenuData.name
      this.editForm.pid = this.editMenuData.pid
      setTimeout(() => {
        this.$refs.editForm.clearValidate()
      }, 0)
    }
  },
  methods: {
    /**
     * 保存
     */
    save () {
      if (this.disabled) {
        return
      }
      this.$refs.editForm.validate(valid => {
        if (!valid) {
          return false
        }
        this.disabled = true
        this.$api
          .updateUserGroupById({
            data: this.editForm
          })
          .then(res => {
            this.disabled = false
            if (!res.success) {
              return
            }
            this.$emit('close', res.data || {})
            this.$notifyBox('修改成功', 'success')
          })
      })
    },
    /**
     * 取消
     */
    cancel () {
      this.$emit('close', false)
    }
  }
}
</script>
